package com.imy.lua;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import com.immomo.mls.InitData;
import com.immomo.mls.MLSBundleUtils;
import com.immomo.mls.MLSEngine;
import com.immomo.mls.activity.LuaViewActivity;
import com.immomo.mls.fun.lt.SIApplication;
import com.immomo.mls.global.LVConfigBuilder;

import com.imy.common.helper.PermissionHelper;
import com.imy.common.util.ALog;
import com.imy.common.util.ToastUtil;
import com.imy.lua.activity.LuaActivity;
import com.imy.lua.exception.LuaException;
import com.imy.lua.helper.properties.PropertiesLoaderHelper;
import com.imy.lua.interfaces.CallAccessibilityServiceListener;
import com.imy.lua.lib.RegisterManger;
import com.imy.lua.provider.GlideImageProvider;
import com.imy.lua.view.floating.FloatingManger;

import org.luaj.vm2.Globals;
import org.opencv.android.OpenCVLoader;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;


import static com.immomo.mls.Constants.ASSETS_PREFIX;

/**
 * @ProjectName: LuaScript
 * @Package: com.imy.lua
 * @ClassName: LuaCore
 * @Description: 描述
 * @Author: Imy
 * @CreateDate: 2021/4/17 15:13
 */
public class LuaCore {
    private static volatile LuaCore gCore = new LuaCore();
    public String SD_CARD_PATH;

    private Handler mainHandler = new Handler(Looper.getMainLooper());

    public List<String> getWatList() {
        return watList;
    }

    private List<String> watList = new ArrayList<>();

    public Handler getMainHandler() {
        return mainHandler;
    }

    public static LuaCore get() {
        return gCore;
    }

    private Context mContext;

    public String getPackageNameImpl() {
        String sPackageName = mContext.getPackageName();
        if (sPackageName.contains(":")) {
            sPackageName = sPackageName.substring(0, sPackageName.lastIndexOf(":"));
        }
        return sPackageName;
    }

    public Context getContext() {
        return mContext;
    }

    public void init(Application application) {
        mContext = application;
        /// -----------配合 Application 使用------------
        SIApplication.isColdBoot = true;
        application.registerActivityLifecycleCallbacks(new ActivityLifecycleMonitor());
        SD_CARD_PATH = Environment.getExternalStorageDirectory().getAbsolutePath();
        if (!SD_CARD_PATH.endsWith("/")) {
            SD_CARD_PATH += "/";
        }
        SD_CARD_PATH += "MLN_Android/";
        MLSEngine.init(application, true)
                .setLVConfig(new LVConfigBuilder(application)
                        .setRootDir(SD_CARD_PATH)    //设置lua根目录
                        .setImageDir(SD_CARD_PATH + "image")  //设置lua图片根目录
                        .setCacheDir(SD_CARD_PATH + "cache")  //设置lua缓存目录
                        .setGlobalResourceDir(SD_CARD_PATH + "g_res")    //设置资源文件目录
                        .build())
                .setImageProvider(new GlideImageProvider())//lua加载图片工具，不实现的话，图片无法展示
                .registerUD(RegisterManger.regUD())
                .registerCovert(RegisterManger.registerCovert()) //注册转换器
                .registerSingleInsance(RegisterManger.registerSingleInstance())
                .registerConstants(RegisterManger.registerConstants())
                .registerSC(RegisterManger.registerStaticClass())
                .build(true);
        ALog.i("Lua onCreate: " + Globals.isInit() + " " + Globals.isIs32bit());
        //初始化手势
        //读取配置路径
    }

    public void start(Context context, String path) {
        //判断是否有悬浮窗权限-->
        boolean b = PermissionHelper.requestOverlayPermission((Activity) context);
        if (!b) {
            PermissionHelper.openFloating((Activity) context);
            return;
        }
        //读取global配置
        File file = new File(path);
        ALog.i("start Lua:" + file.exists()+" path:"+file.getAbsolutePath());
        String parent = file.getParent();

        String globalConfig = parent + "/global.properties";
        Properties properties = PropertiesLoaderHelper.loadGlobal(context,globalConfig);
        if (properties == null) {
            ToastUtil.toast(LuaCore.get().getContext(), "当前无配置global.properties请检查文件");
            return;
        }
        //打开悬浮窗
        FloatingManger.get().start();
        Intent intent = new Intent(context, LuaActivity.class);
        InitData initData = MLSBundleUtils.createInitData(path);
        intent.putExtras(MLSBundleUtils.createBundle(initData));
        context.startActivity(intent);
    }

    public void addWatch(String oneArgToString) {
        watList.add(oneArgToString);
    }

    public void setCallAccessibilityServiceListener(CallAccessibilityServiceListener listener) {
        this.accessibilityServiceListener = listener;
    }

    private CallAccessibilityServiceListener accessibilityServiceListener;

    public CallAccessibilityServiceListener getAccessibilityServiceListener() {
        if (accessibilityServiceListener==null){
            //无障碍没开启
            throw new LuaException("无障碍未初始化");
        }
        return accessibilityServiceListener;
    }

    public boolean checkAccessibilityEnable() {
        if (accessibilityServiceListener==null){
            return false;
        }else {
            return true;
        }

    }
}